package com.fr.lintcode;

import org.junit.Test;

/**
*作者：furong
*日期：2017年1月13日
*时间：下午4:11:21
*/
public class Q170 {
    /**
     * @param head: the List
     * @param k: rotate to the right k places
     * @return: the list after rotation
     */
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        int total = 0;
        ListNode p = null;
        ListNode c = head;
        while (c != null) {
            total++;
            p = c;
            c = c.next;

        }
        p.next = head;
        k %= total;
        c = head;
        int count = 0;
        total -= k;
        while (c != null) {
            count++;
            if (count == total) {
                p = c.next;
                c.next = null;
                break;
            }
            c = c.next;
        }
        return p;
    }

    @Test
    public void testA() {
        ListNode head = new ListNode(1);
        ListNode l1 = new ListNode(2);
        ListNode l2 = new ListNode(3);
        ListNode l3 = new ListNode(4);
        ListNode l4 = new ListNode(5);
        ListNode l5 = new ListNode(6);
        ListNode l6 = new ListNode(7);
        head.next = l1;
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l5;
        l5.next = l6;
        int k = 3;
        System.out.println(head);
        ListNode rs = rotateRight(head, k);
        System.out.println(rs);
    }
}
